package cn.fzkj.gulimall.ware.service.impl;

import cn.fzkj.gulimall.ware.vo.SkuStockVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.fzkj.common.utils.PageUtils;
import cn.fzkj.common.utils.Query;

import cn.fzkj.gulimall.ware.dao.WareSkuDao;
import cn.fzkj.gulimall.ware.entity.WareSkuEntity;
import cn.fzkj.gulimall.ware.service.WareSkuService;
import org.springframework.util.CollectionUtils;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    private WareSkuDao wareSkuDao;

    /**
     * 查询skuids 分别是否有库存
     * @param skuIds
     * @return
     */
    @Override
    public List<SkuStockVo> getSkuHasStock(List<Long> skuIds) {

        return baseMapper.getSkuStock(skuIds);
    }

    @Override
    public boolean addStock(Long skuId, Integer skuNum, Long wareId) {

        List<WareSkuEntity> wareSkuEntities = baseMapper.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (CollectionUtils.isEmpty(wareSkuEntities)){
            // 新增
            WareSkuEntity entity = new WareSkuEntity();
            entity.setSkuId(skuId);
            entity.setWareId(wareId);
            entity.setStock(skuNum);
            this.baseMapper.insert(entity);
        }else {
            // 更新
            wareSkuDao.addStock(skuId, skuNum, wareId);
        }

        return true;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        /**
         * skuId:
         * wareId: 1
         */
        String skuId = (String) params.get("skuId");
        if (StringUtils.isNotEmpty(skuId)){
            wrapper.eq("sku_id", skuId);
        }
        String wareId = (String) params.get("wareId");
        if (StringUtils.isNotEmpty(wareId)){
            wrapper.eq("ware_id", wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

}